package com.guaoran.distributed.message.activemq;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * @author : gucheng
 * @Description : <br/>
 *  持久化机制
 * @date :2018/11/8 16:03
 */
public class PersistentProducer {
    public static void main(String[] args) throws JMSException {
        ConnectionFactory connectionFactory =
                new ActiveMQConnectionFactory(CommonUtil.CONNECT_URL);
        Connection connection = null;
        try {
            //创建连接
            connection = connectionFactory.createConnection();
            connection.start();
            //创建session会话
            Session session = connection.createSession(Boolean.TRUE,Session.AUTO_ACKNOWLEDGE);
            //创建目的地
            Destination destination = session.createQueue("myQueue");
            //创建消息发送者
            MessageProducer producer = session.createProducer(destination);
            // 默认是持久化
//            producer.setDeliveryMode(DeliveryMode.PERSISTENT);//持久化到硬盘或文件
            producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);//非持久化，存储在内存中
            //创建消息，并发送
            for (int i = 0; i < 10; i++) {
                TextMessage message = session.createTextMessage("Hello world!"+i);
                producer.send(message);
                session.commit();
            }
            session.close();
        } catch (JMSException e) {
            e.printStackTrace();
        }finally {
            if(connection != null){
                connection.close();
            }
        }
    }
}
